{% extends template_inherits %}

{% block head %}

    <link rel="stylesheet" type="text/css" href="/media/js/ext-3.0.0/resources/css/ext-all.css" />

    <script type="text/javascript" src="/media/js/ext-3.0.0/adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="/media/js/ext-3.0.0/ext-all.js"></script>

    <script type="text/javascript" src="/media/js/utilities.js"></script>

    <script type="text/javascript">

        Ext.onReady(function(){

            // The rstores dictionary is used to store data for the objects relations
            // typically it's rendered in dropdown boxes. Each relation is stored using
            // a SimpleStore.
            var rstores={}
            {% for r in related.items %}
                var store{{ r.0 }} = new Ext.data.SimpleStore({
                    fields: ['id', 'caption'],
                    id:0,
                    data : [
                        {% for i in r.1 %}
                                ['{{ i.0 }}', '{{ i.1 }}'],
                        {% endfor %}
                    ]
                });
                rstores['{{ r.0 }}']=store{{ r.0 }};
            {% endfor %}

            // Prepare a new form
            var form = new Ext.FormPanel({
                labelWidth: 75,
                frame:true,
                border:false,
                defaultType: 'textfield',
                items: [    // This is a little ugly. How can this be improved?
                    {% for f in edit_fields %}
                        {% ifnotequal f.0 'pk' %}
                            {% ifequal f.2 'DateField' %}
                                new Ext.form.DateField({
                                    fieldLabel: '{{ f.0 }}',
                                    name: '{{ f.0 }}',
                                    readOnly: '{{ f.5 }}'=='False',
                                    allowBlank: '{{ f.6 }}'=='True',
                                    format: 'Y-m-d'
                                }),
                            {% else %}
                                {% ifequal f.2 'ForeignKey' %}
                                    new Ext.form.ComboBox({
                                        store:store{{ f.0 }},
                                        name: '{{ f.0 }}',
                                        fieldLabel: '{{ f.0 }}',
                                        displayField:'caption',
                                        hiddenName:'{{ f.0 }}',
                                        valueField:'id',
                                        typeAhead: true,
                                        mode: 'local',
                                        forceSelection: true,
                                        triggerAction: 'all',
                                        emptyText:'Select a {{ f.0 }}...',
                                        selectOnFocus:true
                                    }),

                                {% else %}
                                    new Ext.form.TextField({
                                        fieldLabel: '{{ f.0 }}',
                                        name: '{{ f.0 }}',
                                        readOnly: '{{ f.5 }}'=='False',
                                        allowBlank: '{{ f.6 }}'=='True'
                                    }),
                                {% endifequal %}
                            {% endifequal %}
                        {% else %}
                            new Ext.form.NumberField({
                                fieldLabel: '{{ f.0 }}',
                                name: '{{ f.0 }}',
                                readOnly: true,
                                allowBlank: true
                            }),
                        {% endifnotequal %}
                    {% endfor %}
                ],
                reader: new Ext.data.JsonReader({
                        root: 'results',
                        idProperty: 'pk',
                        totalProperty: 'total',
                        remoteSort: true
                    }, [
                        // Set up the fields mapping
                         {% for f in list_fields %}
                             { name:"{{ f.0 }}", mapping:"{{ f.1 }}"}{% if not forloop.last %},{% endif %}
                         {% endfor %}
                    ])
            });

            // Prepare the submit button.
            var submit = form.addButton({
                text: 'Submit',
                handler: function(){
                    form.getForm().submit({
                        url:'{{ json_save_url }}',
                        waitMsg:'Saving Data...',
                        success:function(form, action) { win.hide(); grid.store.reload() },
                        failure:function(form, action) { alert('Action failed.'); }
                    });
                }
            });


            // Variable to hold the window.
            var win;

            // Function to create and open the window. If record_id<=0 the window
            // will be ready for a new record. If record_id>0 the window will display
            // the object with this record_id.
            var create_form_window = function(record_id){
                // create the window on the first click and reuse on subsequent clicks
                if (!win) {
                    win = new Ext.Window({
                        applyTo:'form-win',
                        layout:'fit',
                        width:500,
                        height:300,
                        closeAction:'hide',
                        plain: true,
                        items: form // The only item in the window is the form.
                    });
                }
                if (record_id>0) {
                    // It's an existing record, load it using ajax.
                    form.getForm().load({url:'{{ json_list_url }}?pk='+record_id, waitMsg:'Loading'});
                } else {
                    form.getForm().reset();
                }
                win.show(this);
            };



            // Variables to hold the selected grid-row and row-id from the grid
            var selected_grid_row=-1;
            var selected_row_id=-1;


            // create the datastore useds by the grid.
            var grid_store = new Ext.data.Store({
                // load using HTTP
                url: '{{ json_list_url }}{{ filter }}',
                remoteSort: true,
                // the return will be JSON, so lets set up a reader
                reader: new Ext.data.JsonReader({
                       root: 'results',
                       idProperty: 'pk',
                       totalProperty: 'total',
                       remoteSort: true
                   }, [
                       // set up the fields mapping
                        {% for f in list_fields %}
                            { name:"{{ f.0 }}", mapping:"{{ f.1 }}"}{% if not forloop.last %},{% endif %}
                        {% endfor %}
                        {% for f in fields_list_methods %}
                            , { name:"{{ f.0 }}", mapping:"fields.{{ f.0 }}"}
                        {% endfor %}


                   ])
            });

            // Defines a function used to convert a foreignkey id to the
            // value of that foreign model object. Using the rstores.
            var relation_renderer = function(data,cell,record,row,col,store) {
                var rel_data='';
                if (data!=null) {
                    // Get the field name.
                    var fieldName=grid.getColumnModel().getDataIndex(col);
                    // Look up the caption in the store.
                    rel_data=rstores[fieldName].getById(data).get('caption');
                }
                return(rel_data);
            }

            // create the grid
            var grid = new Ext.grid.GridPanel({
                title: '{{ caption }}{{ filter_caption }}',
                store: grid_store,
                columns: [
                    {% for f in list_fields %}
                        {% ifequal f.2 'ForeignKey' %}
                            { header:"{{ f.3 }}", dataIndex:"{{ f.0 }}", sortable:true, width:100, renderer:relation_renderer }{% if not forloop.last %},{% endif %}
                        {% else %}
                            { header:"{{ f.3 }}", dataIndex:"{{ f.0 }}", sortable:true, width:100 }{% if not forloop.last %},{% endif %}
                        {% endifequal %}
                    {% endfor %}
                    {% for f in fields_list_methods %}
                            ,{ header:"{{ f.1 }}", dataIndex:"{{ f.0 }}", sortable:false, width:100 }
                    {% endfor %}
                ],
                renderTo:'datadiv1', // place in this element
                width:740,
                height:300,
                // Add the apropriate buttons to the top toolbar.
                tbar: [
                    {% if rights.add %}
                       new Ext.Toolbar.Button({
                            text: 'Add',
                            id:'bAdd',
                            handler: function(){
                                create_form_window(0);
                            }
                        }),
                    {% endif %}
                    {% if rights.edit %}
                       new Ext.Toolbar.Button({
                            text: 'Edit',
                            hidden: true,
                            id:'bEdit',
                            handler: function(){
                                create_form_window(selected_row_id);
                            }
                        }),
                    {% endif %}
                    {% if rights.delete %}
                       new Ext.Toolbar.Button({
                            text: 'Delete',
                            hidden: true,
                            id:'bDelete',
                            handler: function(){
                                grid.getStore().removeAt(selected_grid_row);
                                alert('not implemented');
                            }
                        }),
                    {% endif %}
                    // And even more buttons specified in the model.
                    {% for a in object_actions %}
                        new Ext.Toolbar.Button({
                            text: '{{ a.1 }}',
                            hidden: {% if not a3 %}true{% else %}false{% endif %},
                            id:'b{{ a.1 }}',
                            handler: function(){
                                var url='{{ a.2 }}';
                                url=url.replace("$pk$",selected_row_id)
                                jumpto(url);
                            }
                        }),
                    {% endfor %}
                ],
                // Add a paginator toolbag to the bottom of the grid.
                bbar: new Ext.PagingToolbar({
                           pageSize: {{ page_size }},
                           store: grid_store,
                           displayInfo: true,
                           displayMsg: 'Displaying topics {0} - {1} of {2}',
                           emptyMsg: "No topics to display"
                        })
            }); // end of grid

            // A listener which remembers the currently selected
            // row index and object id.
            var cellclick = function(grid, rowIndex, columnIndex, e) {
                var record = grid.getStore().getAt(rowIndex);  // Get the Record
                //var fieldName = grid.getColumnModel().getDataIndex(columnIndex); // Get field name
                //var data = record.get(fieldName);
                selected_grid_row=rowIndex;
                selected_row_id=record.get('pk');
                Ext.getCmp('bEdit').show();
                Ext.getCmp('bDelete').show();
                {% for a in object_actions %}
                    Ext.getCmp('b{{ a.1 }}').show();
                {% endfor %}
            }
            grid.addListener('cellclick', cellclick );

            // Ext.getCmp('bDelete').addListener('click', delete_click );

            // Load the initial grid data.
            grid_store.load({params:{start:0, limit:{{ page_size }} } });

        });

    </script>

{% endblock %}


{% block content %}

    <p>{{ description }}</p>

    <br>

    <div id="datadiv1" style=""></div>

    <div id="form-win" class="x-hidden">
        <div class="x-window-header">Add / edit {{ model }}</div>
    </div>

{% endblock %}
